//
//  VRViewMonitorViewController.m
//  VRFirefighting
//
//  Created by Veer on 2018/8/22.
//  Copyright © 2018年 Veer. All rights reserved.
//

#import "VRViewMonitorViewController.h"
#import "VRViewBackVideoViewController.h"

#import "XDropMenuView.h"
#import "VRDeviceDataCell.h"

#import "VRDeviceDataModel.h"
#import <EZUIKit.h>
#import <EZUIPlayer.h>
#import "EZUIError.h"
#import "Toast+UIView.h"

@interface VRViewMonitorViewController () <XDropMenuViewDelegate, EZUIPlayerDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *listBgView;
@property (nonatomic, strong) XDropMenuView *dropMenu;
@property (nonatomic, strong) UILabel *typeTitleLbl;
@property (nonatomic, strong) UIButton *viewBackVideoBtn;

@property (nonatomic, strong) NSArray<VRDeviceDataModel *> *deviceDataModelArray;

@property (nonatomic, copy) NSString *class0;
@property (nonatomic, copy) NSString *ModelName;

@property (nonatomic, strong) EZUIPlayer *mPlayer;
@property (nonatomic, copy) NSString *key;
@property (nonatomic, copy) NSString *token;
@property (nonatomic, copy) NSString *ezopenUrl;

@end

@implementation VRViewMonitorViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"查看监控";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupSubView];
    [self setupListMenu];
    [self getDeviceType];
}

- (void)dealloc
{
    [self releasePlayer];
}

- (void)setupSubView
{
//    self.tableView.y = NAVIGATION_BAR_HEIGHT + 64;
    UIButton *viewBackVideoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    viewBackVideoBtn.backgroundColor = RGB(200, 200, 200);
    viewBackVideoBtn.layer.cornerRadius = 4;
    [viewBackVideoBtn setTitle:@"查看监控回放" forState:UIControlStateNormal];
    viewBackVideoBtn.titleLabel.font = VRFont(16);
    [viewBackVideoBtn setTitleColor:RGB(51, 51, 51) forState:UIControlStateNormal];
    [viewBackVideoBtn setTitleColor:RGB(120, 120, 120) forState:UIControlStateHighlighted];
    [viewBackVideoBtn addTarget:self action:@selector(onViewBackVideoBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:viewBackVideoBtn];
    self.viewBackVideoBtn = viewBackVideoBtn;
    [viewBackVideoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.mPlayer.previewView.mas_bottom).offset(20);
        make.width.mas_equalTo(kScreenWidth - 80);
        make.height.mas_equalTo(46);
    }];
}

- (void)setupListMenu
{
    
    UIView *listBgView = [[UIView alloc] init];
    listBgView.backgroundColor = RGB(255, 255, 255);
    listBgView.frame = CGRectMake(0, NAVIGATION_BAR_HEIGHT, kScreenWidth, 64);
    [self.view addSubview:listBgView];
    self.listBgView = listBgView;
    
    UIView *listView = [[UIView alloc] init];
    listView.layer.borderColor = MAINColor.CGColor;
    listView.layer.borderWidth = 1.0;
    listView.frame = CGRectMake(0, 0, kScreenWidth - 20 * 2, 40);
    listView.center = CGPointMake(kScreenWidth * 0.5, 32);
    [listBgView addSubview:listView];
    
    UILabel *detailLbl = [[UILabel alloc] init];
    detailLbl.text = @"监控设备选择";
    detailLbl.textColor = RGB(80, 80, 80);
    detailLbl.font = VRFont(14);
    //    detailLbl.textAlignment = NSTextAlignmentRight;
    detailLbl.frame = CGRectMake(8, 0, 100, 40);
    [listView addSubview:detailLbl];
    
    //列表展示的模型
    NSMutableArray *section1Datas = [NSMutableArray array];
    
    //    NSArray *title1Array = @[@"智慧烟感监测", @"智慧气感监测"];
    //    for (NSString *str in title1Array) {
    //        XMenuModel *model = [[XMenuModel alloc] init];
    //        model.name = str;
    //        model.id = 0;
    //        [section1Datas addObject:model];
    //    }
    
    NSMutableArray *allDatas = [NSMutableArray array];
    [allDatas addObject:section1Datas];
    
    //上边按钮展示的模型,此模型对text赋值即可.
    NSArray *titleArray = @[@"暂无监控设备"];
    
    //若列表展示内容与按钮展示内容相同则showArr传nil即可。
    XDropMenuView *dropMenu = [[XDropMenuView alloc] initWithFrame:CGRectMake(88, 0, listView.width - 88, 40) showOnView:self.view AllDataArr:allDatas showArr:[titleArray copy]];
    dropMenu.itemNormalColor = MAINColor;
    dropMenu.itemSelectedColor = MAINColor;
    dropMenu.titleNormalColor = MAINColor;
    dropMenu.titleSelectedColor = MAINColor;
    dropMenu.fonteSize = 14;
    dropMenu.delegate = self;
    [listView addSubview:dropMenu];
    self.dropMenu = dropMenu;
}


- (void)setupPlayer
{
    
    if (self.mPlayer == nil) {
        
        self.mPlayer = [[EZUIPlayer alloc] init];
        self.mPlayer.mDelegate = self;
        //添加预览视图到当前界面
        self.mPlayer.previewView.frame = CGRectMake(20, NAVIGATION_BAR_HEIGHT + 64 +20, kScreenWidth - 40, CGRectGetHeight(self.mPlayer.previewView.frame));
        self.mPlayer.customIndicatorView.centerX = (kScreenWidth - 40) * 0.5;
        [self.view insertSubview:self.mPlayer.previewView belowSubview:self.listBgView];
    }
    
    //初始化
    [EZUIKit initWithAppKey:self.key];
    //登录授权
    [EZUIKit setAccessToken:self.token];
    //创建播放器
    
    [self.mPlayer setEZOpenUrl:self.ezopenUrl];
    
    //开始播放，回放模式必须在EZUIPlayerPrepared回调之后再进行调用
    [self.mPlayer startPlay];
//
//    [self.view bringSubviewToFront:self.listBgView];
//    [self.view bringSubviewToFront:self.dropMenu];
}

- (void) releasePlayer
{
    if (self.mPlayer)
    {
        [self.mPlayer.previewView removeFromSuperview];
        [self.mPlayer releasePlayer];
        self.mPlayer = nil;
    }
}


#pragma mark - networking
- (void)getDeviceType
{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"UserID"] = [VRUser shareUser].token;
    param[@"fIsAreaManage"] = @([VRUser shareUser].fIsAreaManage);
    
    weakify(self)
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    //    hud.bezelView.backgroundColor = RGBA(0, 0, 0, 0.9);
    //    hud.bezelView.style = MBProgressHUDBackgroundStyleBlur;
    hud.mode = MBProgressHUDModeIndeterminate;
    [JKNetworking postWithSign:GetMonitorTask parameters:param success:^(NSDictionary *responseObject) {
        
        strongify(self)
        NSLog(@"responseObject:%@", responseObject);
        NSInteger code = [responseObject[@"state"] integerValue];
        NSString *msg = responseObject[@"message"];
        
        if (code == 0) {
            
            //            self.deviceDataModelArray = [VRDeviceDataModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            NSMutableArray *section1Datas = [NSMutableArray array];
            NSArray *dictArray = responseObject[@"data"];
            for (NSDictionary *dict in dictArray) {
                
                XMenuModel *model = [[XMenuModel alloc] init];
                model.name = dict[@"fFacilityModelID"];
                model.id = dict[@"fID"];
                [section1Datas addObject:model];
            }
            NSMutableArray *allDatas = [NSMutableArray array];
            [allDatas addObject:section1Datas];
            
            if (section1Datas.count > 0) {
                
                self.class0 = [section1Datas.firstObject id];
                self.ModelName = [section1Datas.firstObject name];
                [self getDeviceDataWithType:[section1Datas.firstObject id]];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                
                self.viewBackVideoBtn.hidden = section1Datas.count == 0;
                self.dropMenu.AllDataArr = allDatas;
                if(section1Datas.count){
                    [self.dropMenu selectClum:0 Row:0];
                }
                [hud hideAnimated:YES];
            });
        }else if(msg.length > 0){
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:msg];
                [hud hideAnimated:YES];
            });
        }
    } error:^(NSError * _Nonnull error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:@"未知错误"];
            [hud hideAnimated:YES];
            [self.tableView.mj_header endRefreshing];
        });
    }];
}


- (void)getDeviceDataWithType:(NSString *)type
{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
//    param[@"UserID"] = [VRUser shareUser].token;
//    param[@"fIsAreaManage"] = @([VRUser shareUser].fIsAreaManage);
    param[@"fID"] = type;
    
    weakify(self)
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    //    hud.bezelView.backgroundColor = RGBA(0, 0, 0, 0.9);
    //    hud.bezelView.style = MBProgressHUDBackgroundStyleBlur;
    hud.mode = MBProgressHUDModeIndeterminate;
    [JKNetworking postWithSign:GetMonitorVideo parameters:param success:^(NSDictionary *responseObject) {
        
        strongify(self)
        NSLog(@"responseObject:%@", responseObject);
        NSInteger code = [responseObject[@"state"] integerValue];
        NSString *msg = responseObject[@"message"];
        
        if (code == 0) {
            
            NSString *key = responseObject[@"data"][@"appKey"];
            NSString *token = responseObject[@"data"][@"token"];
            NSString *ezopenUrl = responseObject[@"data"][@"ezopenUrl"];
            self.key = key;
            self.token = token;
            self.ezopenUrl = ezopenUrl;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self setupPlayer];
//                [self.tableView reloadData];
                [hud hideAnimated:YES];
            });
        }else if(msg.length > 0){
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:msg];
                [hud hideAnimated:YES];
            });
        }
        [self.tableView.mj_header endRefreshing];
    } error:^(NSError * _Nonnull error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:@"未知错误"];
            [hud hideAnimated:YES];
            [self.tableView.mj_header endRefreshing];
        });
    }];
}


#pragma mark - action
- (void)onViewBackVideoBtnClick:(UIButton *)sender
{
    VRViewBackVideoViewController *backVc = [[VRViewBackVideoViewController alloc] init];
    backVc.fID = self.class0;
    backVc.ModelName = self.ModelName;
    [self.navigationController pushViewController:backVc animated:YES];
}


#pragma mark - player delegate

- (void) EZUIPlayerFinished:(EZUIPlayer*) player
{
    [player stopPlay];
   
}

- (void) EZUIPlayerPrepared:(EZUIPlayer*) player
{
    [player startPlay];
}

- (void) EZUIPlayerPlaySucceed:(EZUIPlayer *)player
{

}

- (void) EZUIPlayer:(EZUIPlayer *)player didPlayFailed:(EZUIError *) error
{
    [player stopPlay];

    if ([error.errorString isEqualToString:UE_ERROR_INNER_VERIFYCODE_ERROR])
    {
        [self.view makeToast:[NSString stringWithFormat:@"%@(%@[%ld])", @"验证码错误",
                              error.errorString,
                              error.internalErrorCode]
                    duration:1.5
                    position:@"center"];
    }
    else if ([error.errorString isEqualToString:UE_ERROR_TRANSF_DEVICE_OFFLINE])
    {
        [self.view makeToast:[NSString stringWithFormat:@"%@(%@[%ld])",
                              @"设备不在线",
                              error.errorString,
                              error.internalErrorCode]
                    duration:1.5
                    position:@"center"];
    }
    else if ([error.errorString isEqualToString:UE_ERROR_DEVICE_NOT_EXIST])
    {
        [self.view makeToast:[NSString stringWithFormat:@"%@(%@[%ld])",
                              @"设备不存在",
                              error.errorString,
                              error.internalErrorCode]
                    duration:1.5
                    position:@"center"];
    }
    else if ([error.errorString isEqualToString:UE_ERROR_CAMERA_NOT_EXIST])
    {
        [self.view makeToast:[NSString stringWithFormat:@"%@(%@[%ld])",
                              @"通道不存在",
                              error.errorString,
                              error.internalErrorCode]
                    duration:1.5
                    position:@"center"];
    }
    else if ([error.errorString isEqualToString:UE_ERROR_INNER_STREAM_TIMEOUT])
    {
        [self.view makeToast:[NSString stringWithFormat:@"%@(%@[%ld])",
                              @"连接超时",
                              error.errorString,error.internalErrorCode]
                    duration:1.5
                    position:@"center"];
    }
    else if ([error.errorString isEqualToString:UE_ERROR_CAS_MSG_PU_NO_RESOURCE])
    {
        [self.view makeToast:[NSString stringWithFormat:@"%@(%@[%ld])",
                              @"设备连接数过大",
                              error.errorString,
                              error.internalErrorCode]
                    duration:1.5
                    position:@"center"];
    }
    else if ([error.errorString isEqualToString:UE_ERROR_NOT_FOUND_RECORD_FILES])
    {
        [self.view makeToast:[NSString stringWithFormat:@"%@(%@[%ld])",
                              @"未找到录像文件",
                              error.errorString,
                              error.internalErrorCode]
                    duration:1.5
                    position:@"center"];
    }
    else if ([error.errorString isEqualToString:UE_ERROR_PARAM_ERROR])
    {
        [self.view makeToast:[NSString stringWithFormat:@"%@(%@[%ld])",
                              @"参数错误",
                              error.errorString,
                              error.internalErrorCode]
                    duration:1.5
                    position:@"center"];
    }
    else if ([error.errorString isEqualToString:UE_ERROR_URL_FORMAT_ERROR])
    {
        [self.view makeToast:[NSString stringWithFormat:@"%@(%@[%ld])",
                              @"play_url_format_wrong", @"播放url格式错误",
                              error.errorString,
                              error.internalErrorCode]
                    duration:1.5
                    position:@"center"];
    }
    else
    {
        [self.view makeToast:[NSString stringWithFormat:@"%@(%@[%ld])",
                              @"play_fail", @"播放失败",
                              error.errorString,
                              error.internalErrorCode]
                    duration:1.5
                    position:@"center"];
    }
    
    NSLog(@"play error:%@(%ld)",error.errorString,(long)error.internalErrorCode);
}

- (void) EZUIPlayer:(EZUIPlayer *)player previewWidth:(CGFloat)pWidth previewHeight:(CGFloat)pHeight
{
//    if (self.ezopenUrl)
//    {
//        CGFloat ratio = pWidth/pHeight;
//        CGFloat destWidth = 0,destHeight = 0,px = 0,py = 0;
//        if (ratio < 3/4)
//        {
//            destWidth = [UIScreen mainScreen].bounds.size.width;
//            destHeight = destWidth/ratio;
//            px = 0;
//            py = ([UIScreen mainScreen].bounds.size.width/3*4-destHeight)/2;
//        }
//        else
//        {
//            destHeight = [UIScreen mainScreen].bounds.size.width/3*4;
//            destWidth = destHeight*ratio;
//            px = ([UIScreen mainScreen].bounds.size.width - destWidth)/2;
//            py = 0;
//        }
//        
//        [player setPreviewFrame:CGRectMake(px, py, destWidth, destHeight)];
//    }
//    else
//    {
//        CGFloat ratio = pWidth/pHeight;
//        
//        CGFloat destWidth = CGRectGetWidth(self.view.bounds);
//        CGFloat destHeight = destWidth/ratio;
//        
//        [player setPreviewFrame:CGRectMake(0, CGRectGetMinY(player.previewView.frame), destWidth, destHeight)];
//    }
}


#pragma mark - XDropMenuViewDelegate
- (void)dropMenuView:(XDropMenuView *)dropMenuView didSelectRowAtColum:(NSInteger)colum Row:(NSInteger)row model:(XMenuModel *)model
{
    self.class0 = model.id;;
    self.ModelName = model.name;
    [self getDeviceDataWithType:model.id];
}

- (EZUIPlayer *)mPlayer
{
    if (_mPlayer == nil) {
        
        _mPlayer = [[EZUIPlayer alloc] init];
        _mPlayer.mDelegate = self;
        //添加预览视图到当前界面
        _mPlayer.previewView.frame = CGRectMake(20, NAVIGATION_BAR_HEIGHT + 64 +20, kScreenWidth - 40, CGRectGetHeight(_mPlayer.previewView.frame));
        _mPlayer.customIndicatorView.centerX = (kScreenWidth - 40) * 0.5;
//        [self.view insertSubview:_mPlayer.previewView belowSubview:self.listBgView];
        [self.view addSubview:_mPlayer.previewView];
    }
    return _mPlayer;
}



@end
